<?php

class Admin_GeneratorController extends CMS_Controller_Action_Admin {

    protected $arrayTypes = array("text" => array("dbType" => "varchar(250)", "fieldType" => "text"),
                                  "date" => array( "dbType" => "datetime", "fieldType" => "text" ),
                                  "checkbox" => array("dbType" => "tinyint(4)", "fieldType" => "checkbox" ),
                                  "editor" => array("dbType" => "text" , "fieldType" => "textarea"),
                                  "file" => array("dbType" => "varchar(250)" , "fieldType" => "file") );

    public function init() {
        parent::init();
    }

    public function indexAction() {

    }

    public function simpleAction() {
        $form = $this->langCategoryForm("simple");
        $this->view->form = $form;
        if (!$this->getRequest()->isPost()) {
            return;
        } else {
            if (!$form->isValid($_POST)) {
                $this->view->form = $form;
                return;
            } else {
                $values = $form->getValues();
                $module = new CMS_Models_Module();
                $module = $module->createRow();
                $module->name = $values['common']['name'];
                $module->action = $values['common']['system_name'];
                $module->system_name = $values['common']['system_name'];
                $module->id_module = $values['common']['parent'];
                $module->plural_name = $values['common']['plural'];
                $module->save();
                $this->generateSimpleFiles($module, $values['common']['fields']);
                $this->_redirect("/admin/generator");
            }
        }
    }

    public function langsimpleAction() {
        $form = $this->simpleLangForm("langsimple");
        $this->view->form = $form;
        if (!$this->getRequest()->isPost()) {
            return;
        } else {
            if (!$form->isValid($_POST)) {
                $this->view->form = $form;
                return;
            } else {
                $values = $form->getValues();
                $module = new CMS_Models_Module();
                $module = $module->createRow();
                $module->name = $values['common']['name'];
                $module->action = $values['common']['system_name'];
                $module->system_name = $values['common']['system_name'];
                $module->id_module = $values['common']['parent'];
                $module->plural_name = $values['common']['plural'];
                $module->save();
                $this->generateLangSimpleFiles($module,$values['common']['fields'], $values['common']['langFields']);
                $this->_redirect("/admin/generator");
            }
        }
    }

    /**
     * Carga de un modulo categorizado con idiomas.
     */
    public function langcategoryAction() {
        $form = $this->langCategoryForm("langcategory");
        $this->view->form = $form;
        if (!$this->getRequest()->isPost()) {
            return;
        } else {
            if (!$form->isValid($_POST)) {
                $this->view->form = $form;
                return;
            } else {
                $values = $form->getValues();
                $module = new CMS_Models_Module();
                $module = $module->createRow();
                $module->name = $values['common']['name'];
                $module->action = $values['common']['system_name'];
                $module->system_name = $values['common']['system_name'];
                $module->id_module = $values['common']['parent'];
                $module->plural_name = $values['common']['plural'];
                $module->save();
                $this->generateLangCategoryFiles($module,$values['common']['fields'], $values['common']['langFields']);
                $this->_redirect("/admin/generator");
            }
        }
    }

    /**
     * Genera los archivos que necesita el modulo para funcionar
     * basado en las platillas que se encuentran en
     * /application/templates
     * @param Zend_Models_Module $data
     */
    private function generateSimpleFiles($data, $json) {
        if (!file_exists(SYSTEM_PATH . "/application/modules/admin/views/scripts/" . $data->system_name))
            mkdir(SYSTEM_PATH . "/application/modules/admin/views/scripts/" . $data->system_name);
        /*** Archivos de vistas ***/
        $index = fopen(SYSTEM_PATH . "/application/templates/category_lang/views/listmodule.phtml", "r");
        $indexContent = fread($index, filesize(SYSTEM_PATH . "/application/templates/category_lang/views/listmodule.phtml"));
        $indexContent = $this->replaceContents($indexContent, $data);
        $indexFile = fopen(SYSTEM_PATH . "/application/modules/admin/views/scripts/" . $data->system_name . "/index.phtml", "a+");
        fwrite($indexFile, $indexContent);
        fclose($indexFile);

        $edit = fopen(SYSTEM_PATH . "/application/templates/category_lang/views/simpleedit.phtml", "r");
        $editContent = fread($edit, filesize(SYSTEM_PATH . "/application/templates/category_lang/views/simpleedit.phtml"));
        $editContent = $this->replaceContents($editContent, $data);
        $editFile = fopen(SYSTEM_PATH . "/application/modules/admin/views/scripts/" . $data->system_name . "/edit" . $data->system_name . ".phtml", "a+");
        fwrite($editFile, $editContent);
        fclose($editFile);

        $new = fopen(SYSTEM_PATH . "/application/templates/category_lang/views/simpleadd.phtml", "r");
        $newContent = fread($new, filesize(SYSTEM_PATH . "/application/templates/category_lang/views/simpleadd.phtml"));
        $newContent = $this->replaceContents($newContent, $data);
        $newFile = fopen(SYSTEM_PATH . "/application/modules/admin/views/scripts/" . $data->system_name . "/new" . $data->system_name . ".phtml", "a+");
        fwrite($newFile, $newContent);
        fclose($newFile);
        /*         * ************** Fin vistas ************** */
        /*         * ************* Controlador ************** */
        $controller = fopen(SYSTEM_PATH . "/application/templates/category_lang/simple.txt", "r");
        $controllerContent = fread($controller, filesize(SYSTEM_PATH . "/application/templates/category_lang/simple.txt"));
        $controllerContent = $this->replaceContents($controllerContent, $data);
        $json = json_decode($json);
        $controllerContent = $this->replaceFields($json, $controllerContent);
        $controllerContent = $this->generateFormFields($json, $controllerContent);
        $controllerContent = $this->setValuesStatements($json, $controllerContent, $data->system_name);
        $controllerFile = fopen(SYSTEM_PATH . "/application/modules/admin/controllers/" . ucwords($data->system_name) . "Controller.php", "a+");
        fwrite($controllerFile, $controllerContent);
        fclose($controllerFile);
        /*         * ************ Fin Controlador ********** */
        /*         * ************ Modelos ***************** */
        $module = fopen(SYSTEM_PATH . "/application/templates/category_lang/models/module.php", "r");
        $moduleContent = fread($module, filesize(SYSTEM_PATH . "/application/templates/category_lang/models/module.php"));
        $moduleContent = $this->replaceContents($moduleContent, $data);
        $moduleFile = fopen(SYSTEM_PATH . "/library/CMS/Models/" . ucwords($data->system_name) . ".php", "a+");
        fwrite($moduleFile, $moduleContent);
        fclose($moduleFile);
        /*         * ************** Fin modelos ****************** */
        $sql = "CREATE TABLE `" . $data->system_name . "` (
  			  `id` bigint(20) NOT NULL AUTO_INCREMENT,
                           ##otherFields##
  			   PRIMARY KEY (`id`)
			) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=latin1 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC;
			";
        $sql = $this->generateQuery($sql,$json);
        CMS_Db::getInstance()->query($sql);
    }

    private function setLangValuesStatements($json,$string,$name)
    {
        $fields = "";
       foreach( $json as $j )
       {
        if ( $j->type != "date" )
            $code = '$'.$j->name.'->setValue($lang'.$name.'["'.$j->name.'"]);'."\r\n";
        else
            $code = '$'.$j->name.'->setValue(Common_View_Formatter_Date::getDateFromISO8601($lang'.$name.'["'.$j->name.'"]));'."\r\n";

        $fields .= $code;
       }
       return str_replace("##formLangValues##", $fields, $string);
    }

    private function setValuesStatements( $json, $string, $name )
    {
       $fields = "";
       foreach( $json as $j )
       {
        if ( $j->type != "date" )
            $code = '$'.$j->name.'->setValue($'.$name.'->'.$j->name.');'."\r\n";
        else
            $code = '$'.$j->name.'->setValue(Common_View_Formatter_Date::getDateFromISO8601($'.$name.'->'.$j->name.'));'."\r\n";

        $fields .= $code;
       }
       return str_replace("##formValues##", $fields, $string);
    }

    /**
     * Genera el codigo de la creacion de un formulario
     * @param <type> $json
     * @param <type> $string
     * @return <type>
     */
    private function generateFormFields( $json, $string)
    {
       $fields = "";
       foreach( $json as $j )
       {
           $code = '$'.$j->name . ' = $common->createElement("'.$this->arrayTypes[$j->type]['fieldType'].'", "'.$j->name.'");'."\r\n"  ;
           $code .= '$'.$j->name.'->setLabel("'.$j->label.':");'."\r\n";
           if ( $j->type != "checkbox" )
            $code .= '$'.$j->name.'->setAttrib("class","text-long");'."\r\n";
           if ( $j->type == "editor" )
              $code .=  '$'.$j->name.'->setAttrib("class","text-long mceAdvanced");'."\r\n";
           if ( $j->type == "date" )
               $code .=  '$'.$j->name.'->setAttrib("class","text-long dateAdmin");'."\r\n";
           if ( $j->obligatory == 1 )
           {
             $code .= '$'.$j->name.'->addValidator("NotEmpty")->setLabel("'.$j->label.':")->setRequired(true);'."\r\n";
             $code .= '$'.$j->name.'->addErrorMessage("Este_campo_es_obligatorio");'."\r\n";
           }
           $code .= '$common->addElement($'.$j->name.');'."\r\n";
           $fields .= $code;
       }
       return str_replace("##formFields##", $fields, $string);
    }

    private function generateFormLangFields( $json, $string)
    {
       $fields = "";
       foreach( $json as $j )
       {
           $code = '$'.$j->name . ' = $sub->createElement("'.$this->arrayTypes[$j->type]['fieldType'].'", "'.$j->name.'_".$l["prefix2"]);'."\r\n"  ;
           $code .= '$'.$j->name.'->setLabel("'.$j->label.':");'."\r\n";
           if ( $j->type != "checkbox" )
            $code .= '$'.$j->name.'->setAttrib("class","text-long");'."\r\n";
           if ( $j->type == "editor" )
              $code .=  '$'.$j->name.'->setAttrib("class","text-long mceAdvanced");'."\r\n";
           if ( $j->type == "date" )
               $code .=  '$'.$j->name.'->setAttrib("class","text-long dateAdmin");'."\r\n";
           if ( $j->obligatory == 1 )
           {
             $code .= '$'.$j->name.'->addValidator("NotEmpty")->setLabel("'.$j->label.':")->setRequired(true);'."\r\n";
             $code .= '$'.$j->name.'->addErrorMessage("Este_campo_es_obligatorio");'."\r\n";
           }
           $code .= '$sub->addElement($'.$j->name.');'."\r\n";
           $fields .= $code;
       }
       return str_replace("##formLangFields##", $fields, $string);
    }

    /**
     * Reemplaza los campos en una query de create table
     * @param <type> $q
     * @param <type> $json
     * @return <type>
     */
    private function generateQuery($q, $json)
    {
        $fields = "";
        foreach ( $json as $j )
        {
            $code = '`'.$j->name.'`'. '  '. $this->arrayTypes[$j->type]['dbType'];
            if ( $j->obligatory == 1 )
                $code .= "  NOT NULL";
            /*if ( $j->default != "" )
                $code .= "  DEFAULT '".$j->default."'";*/
            $code .= ", ";
            $fields .= $code;
        }
        return str_replace("##otherFields##", $fields, $q);
    }
    /**
     * Agrega los set de los campos en los metodos de guardado y actualizado
     * @param <type> $json
     * @param <type> $string
     * @return <type>
     */
    private function replaceFields($json, $string)
    {
        $fields = "";
        foreach ( $json as $j )
        {
            if ( $j->type != "date" )
                $code = '$content->'.$j->name."= " . '$values["common"]["'.$j->name.'"];'."\r\n";
            else
                $code = '$content->'.$j->name."= " . 'Common_View_Formatter_Date::getDateFromDefault($values["common"]["'.$j->name.'"]);'."\r\n";
            $fields .= $code;
        }
        return str_replace("##fields##", $fields, $string);
    }

    private function replaceLangFields($json, $string, $name)
    {
        $fields = "";
        foreach ( $json as $j )
        {
            if ( $j->type != "date" )
                $code = '$lang'.$name.'->'.$j->name." = " . '$values[$l["prefix2"]]["'.$j->name.'_".$l["prefix2"]];'."\r\n";
            else
                $code = '$lang'.$name.'->'.$j->name." = " . 'Common_View_Formatter_Date::getDateFromDefault($values[$l["prefix2"]]["'.$j->name.'_".$l["prefix2"]]);'."\r\n";
            $fields .= $code;
        }
        return str_replace("##langFields##", $fields, $string);
    }

    /**
     * Genera los archivos que necesita el modulo para funcionar
     * basado en las platillas que se encuentran en
     * /application/templates
     * @param Zend_Models_Module $data
     */
    private function generateLangSimpleFiles($data, $json, $langJson)
    {
       if (!file_exists(SYSTEM_PATH . "/application/modules/admin/views/scripts/" . $data->system_name))
            mkdir(SYSTEM_PATH . "/application/modules/admin/views/scripts/" . $data->system_name);
        /*         * * Archivos de vistas ** */
        $index = fopen(SYSTEM_PATH . "/application/templates/category_lang/views/listmodule.phtml", "r");
        $indexContent = fread($index, filesize(SYSTEM_PATH . "/application/templates/category_lang/views/listmodule.phtml"));
        $indexContent = $this->replaceContents($indexContent, $data);
        $indexFile = fopen(SYSTEM_PATH . "/application/modules/admin/views/scripts/" . $data->system_name . "/index.phtml", "a+");
        fwrite($indexFile, $indexContent);
        fclose($indexFile);

        $edit = fopen(SYSTEM_PATH . "/application/templates/category_lang/views/editmodule.phtml", "r");
        $editContent = fread($edit, filesize(SYSTEM_PATH . "/application/templates/category_lang/views/editmodule.phtml"));
        $editContent = $this->replaceContents($editContent, $data);
        $editFile = fopen(SYSTEM_PATH . "/application/modules/admin/views/scripts/" . $data->system_name . "/edit" . $data->system_name . ".phtml", "a+");
        fwrite($editFile, $editContent);
        fclose($editFile);

        $new = fopen(SYSTEM_PATH . "/application/templates/category_lang/views/newmodule.phtml", "r");
        $newContent = fread($new, filesize(SYSTEM_PATH . "/application/templates/category_lang/views/newmodule.phtml"));
        $newContent = $this->replaceContents($newContent, $data);
        $newFile = fopen(SYSTEM_PATH . "/application/modules/admin/views/scripts/" . $data->system_name . "/new" . $data->system_name . ".phtml", "a+");
        fwrite($newFile, $newContent);
        fclose($newFile);
        /*         * ************** Fin vistas ************** */
        /*         * ************* Controlador ************** */
        $json = json_decode($json);
        $langJson = json_decode($langJson);
        $controller = fopen(SYSTEM_PATH . "/application/templates/category_lang/langSimpleController.txt", "r");
        $controllerContent = fread($controller, filesize(SYSTEM_PATH . "/application/templates/category_lang/controller.txt"));
        $controllerContent = $this->replaceContents($controllerContent, $data);
        $controllerContent = $this->replaceFields($json, $controllerContent);
        $controllerContent = $this->replaceLangFields($langJson, $controllerContent,ucwords($data->system_name));
        $controllerContent = $this->generateFormFields($json, $controllerContent);
        $controllerContent = $this->generateFormLangFields($langJson, $controllerContent);
        $controllerContent = $this->setValuesStatements($json, $controllerContent, $data->system_name);
        $controllerContent = $this->setLangValuesStatements($langJson, $controllerContent, ucwords($data->system_name));
        //echo $controllerContent; exit;
        $controllerFile = fopen(SYSTEM_PATH . "/application/modules/admin/controllers/" . ucwords($data->system_name) . "Controller.php", "a+");
        fwrite($controllerFile, $controllerContent);
        fclose($controllerFile);
        /************** Fin Controlador ***********/
        /************** Modelos ******************/
        $module = fopen(SYSTEM_PATH . "/application/templates/category_lang/models/module.php", "r");
        $moduleContent = fread($module, filesize(SYSTEM_PATH . "/application/templates/category_lang/models/module.php"));
        $moduleContent = $this->replaceContents($moduleContent, $data);
        $moduleFile = fopen(SYSTEM_PATH . "/library/CMS/Models/" . ucwords($data->system_name) . ".php", "a+");
        fwrite($moduleFile, $moduleContent);
        fclose($moduleFile);

        $langModule = fopen(SYSTEM_PATH . "/application/templates/category_lang/models/Langmodule.php", "r");
        $langModuleContent = fread($langModule, filesize(SYSTEM_PATH . "/application/templates/category_lang/models/Langmodule.php"));
        $langModuleContent = $this->replaceContents($langModuleContent, $data);
        $langModuleFile = fopen(SYSTEM_PATH . "/library/CMS/Models/Lang" . ucwords($data->system_name) . ".php", "a+");
        fwrite($langModuleFile, $langModuleContent);
        fclose($langModuleFile);
        /*         * ************** Fin modelos ****************** */
        
        $sql = "CREATE TABLE `" . $data->system_name . "` (
  			  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  			  ##otherFields##
  			   PRIMARY KEY (`id`)
			) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=latin1 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC;";
        $sqlLang = "
            CREATE TABLE `lang_" . $data->system_name . "` (
  				`id_" . $data->system_name . "` bigint(20) NOT NULL,
  				`lang` varchar(2) NOT NULL,
  				##otherFields##
  				PRIMARY KEY (`id_" . $data->system_name . "`,`lang`)
			) ENGINE=InnoDB DEFAULT CHARSET=latin1 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC;
			";
         $sql = $this->generateQuery($sql,$json).$this->generateQuery($sqlLang, $langJson) ;
         
        CMS_Db::getInstance()->query($sql);
    }

    /**
     * Genera los archivos que necesita el modulo para funcionar
     * basado en las platillas que se encuentran en
     * /application/templates
     * @param Zend_Models_Module $data
     */
    private function generateLangCategoryFiles($data , $json, $langJson) {
        /*         * * Genero directorio de las vistas ** */
        if (!file_exists(SYSTEM_PATH . "/application/modules/admin/views/scripts/" . $data->system_name))
            mkdir(SYSTEM_PATH . "/application/modules/admin/views/scripts/" . $data->system_name);
        /*         * * Archivos de vistas ** */
        $newCategory = fopen(SYSTEM_PATH . "/application/templates/category_lang/views/newcategory.phtml", "r");
        $newCategoryContent = fread($newCategory, filesize(SYSTEM_PATH . "/application/templates/category_lang/views/newcategory.phtml"));
        $newCategoryContent = $this->replaceContents($newCategoryContent, $data);
        $newCategoryFile = fopen(SYSTEM_PATH . "/application/modules/admin/views/scripts/" . $data->system_name . "/newcategory.phtml", "a+");
        fwrite($newCategoryFile, $newCategoryContent);
        fclose($newCategoryFile);

        $editCategory = fopen(SYSTEM_PATH . "/application/templates/category_lang/views/editcategory.phtml", "r");
        $editCategoryContent = fread($editCategory, filesize(SYSTEM_PATH . "/application/templates/category_lang/views/editcategory.phtml"));
        $editCategoryContent = $this->replaceContents($editCategoryContent, $data);
        $editCategoryFile = fopen(SYSTEM_PATH . "/application/modules/admin/views/scripts/" . $data->system_name . "/editcategory.phtml", "a+");
        fwrite($editCategoryFile, $editCategoryContent);
        fclose($editCategoryFile);

        $index = fopen(SYSTEM_PATH . "/application/templates/category_lang/views/index.phtml", "r");
        $indexContent = fread($index, filesize(SYSTEM_PATH . "/application/templates/category_lang/views/index.phtml"));
        $indexContent = $this->replaceContents($indexContent, $data);
        $indexFile = fopen(SYSTEM_PATH . "/application/modules/admin/views/scripts/" . $data->system_name . "/index.phtml", "a+");
        fwrite($indexFile, $indexContent);
        fclose($indexFile);

        $list = fopen(SYSTEM_PATH . "/application/templates/category_lang/views/listmodule.phtml", "r");
        $listContent = fread($list, filesize(SYSTEM_PATH . "/application/templates/category_lang/views/listmodule.phtml"));
        $listContent = $this->replaceContents($listContent, $data);
        $listFile = fopen(SYSTEM_PATH . "/application/modules/admin/views/scripts/" . $data->system_name . "/list" . $data->system_name . ".phtml", "a+");
        fwrite($listFile, $listContent);
        fclose($listFile);

        $edit = fopen(SYSTEM_PATH . "/application/templates/category_lang/views/editmodule.phtml", "r");
        $editContent = fread($edit, filesize(SYSTEM_PATH . "/application/templates/category_lang/views/editmodule.phtml"));
        $editContent = $this->replaceContents($editContent, $data);
        $editFile = fopen(SYSTEM_PATH . "/application/modules/admin/views/scripts/" . $data->system_name . "/edit" . $data->system_name . ".phtml", "a+");
        fwrite($editFile, $editContent);
        fclose($editFile);

        $new = fopen(SYSTEM_PATH . "/application/templates/category_lang/views/newmodule.phtml", "r");
        $newContent = fread($new, filesize(SYSTEM_PATH . "/application/templates/category_lang/views/newmodule.phtml"));
        $newContent = $this->replaceContents($newContent, $data);
        
        $newFile = fopen(SYSTEM_PATH . "/application/modules/admin/views/scripts/" . $data->system_name . "/new" . $data->system_name . ".phtml", "a+");
        fwrite($newFile, $newContent);
        fclose($newFile);
        /*         * ************** Fin vistas ************** */
        /*         * ************* Controlador ************** */
        $json = json_decode($json);
        $langJson = json_decode($langJson);
        $controller = fopen(SYSTEM_PATH . "/application/templates/category_lang/controller.txt", "r");
        $controllerContent = fread($controller, filesize(SYSTEM_PATH . "/application/templates/category_lang/controller.txt"));
        $controllerContent = $this->replaceContents($controllerContent, $data);
        $controllerContent = $this->replaceFields($json, $controllerContent);
        $controllerContent = $this->replaceLangFields($langJson, $controllerContent,ucwords($data->system_name));
        $controllerContent = $this->generateFormFields($json, $controllerContent);
        $controllerContent = $this->generateFormLangFields($langJson, $controllerContent);
        $controllerContent = $this->setValuesStatements($json, $controllerContent, $data->system_name);
        $controllerContent = $this->setLangValuesStatements($langJson, $controllerContent, ucwords($data->system_name));
        $controllerFile = fopen(SYSTEM_PATH . "/application/modules/admin/controllers/" . ucwords($data->system_name) . "Controller.php", "a+");
        fwrite($controllerFile, $controllerContent);
        fclose($controllerFile);
        /*         * ************ Fin Controlador ********** */
        /*         * ************ Modelos ***************** */
        $category = fopen(SYSTEM_PATH . "/application/templates/category_lang/models/moduleCategory.php", "r");
        $categoryContent = fread($category, filesize(SYSTEM_PATH . "/application/templates/category_lang/models/moduleCategory.php"));
        $categoryContent = $this->replaceContents($categoryContent, $data);
        $categoryFile = fopen(SYSTEM_PATH . "/library/CMS/Models/" . ucwords($data->system_name) . "Category.php", "a+");
        fwrite($categoryFile, $categoryContent);
        fclose($categoryFile);

        $langCategory = fopen(SYSTEM_PATH . "/application/templates/category_lang/models/LangmoduleCategory.php", "r");
        $langCategoryContent = fread($langCategory, filesize(SYSTEM_PATH . "/application/templates/category_lang/models/LangmoduleCategory.php"));
        $langCategoryContent = $this->replaceContents($langCategoryContent, $data);
        $langCategoryFile = fopen(SYSTEM_PATH . "/library/CMS/Models/Lang" . ucwords($data->system_name) . "Category.php", "a+");
        fwrite($langCategoryFile, $langCategoryContent);
        fclose($langCategoryFile);

        $module = fopen(SYSTEM_PATH . "/application/templates/category_lang/models/module.php", "r");
        $moduleContent = fread($module, filesize(SYSTEM_PATH . "/application/templates/category_lang/models/module.php"));
        $moduleContent = $this->replaceContents($moduleContent, $data);
        $moduleFile = fopen(SYSTEM_PATH . "/library/CMS/Models/" . ucwords($data->system_name) . ".php", "a+");
        fwrite($moduleFile, $moduleContent);
        fclose($moduleFile);

        $langModule = fopen(SYSTEM_PATH . "/application/templates/category_lang/models/Langmodule.php", "r");
        $langModuleContent = fread($langModule, filesize(SYSTEM_PATH . "/application/templates/category_lang/models/Langmodule.php"));
        $langModuleContent = $this->replaceContents($langModuleContent, $data);
        $langModuleFile = fopen(SYSTEM_PATH . "/library/CMS/Models/Lang" . ucwords($data->system_name) . ".php", "a+");
        fwrite($langModuleFile, $langModuleContent);
        fclose($langModuleFile);
        /*         * ************** Fin modelos ****************** */
        $sql = "CREATE TABLE `" . $data->system_name . "` (
  			  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  			  `id_category` bigint(20) NOT NULL,
  			  ##otherFields##
  			   PRIMARY KEY (`id`)
			) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=latin1 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC;
			CREATE TABLE `" . $data->system_name . "_category` (
 			 `id` bigint(20) NOT NULL AUTO_INCREMENT,
  			 `orden` smallint(6) DEFAULT NULL,
  			 `enabled` tinyint(4) DEFAULT NULL,
  			 PRIMARY KEY (`id`)
			) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=latin1 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC;";
        $sqlLang =  "CREATE TABLE `lang_" . $data->system_name . "` (
  				`id_" . $data->system_name . "` bigint(20) NOT NULL,
  				`lang` varchar(2) NOT NULL,
  				##otherFields##
  				PRIMARY KEY (`id_" . $data->system_name . "`,`lang`)
			) ENGINE=InnoDB DEFAULT CHARSET=latin1 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC;
			CREATE TABLE `lang_" . $data->system_name . "_category` (
  				`id_category` bigint(20) NOT NULL,
  				`lang` varchar(2) NOT NULL,
  				`name` varchar(255) DEFAULT NULL,
  				PRIMARY KEY (`id_category`,`lang`)
				) ENGINE=InnoDB DEFAULT CHARSET=latin1 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC;";
        $sql = $this->generateQuery($sql,$json).$this->generateQuery($sqlLang, $langJson) ;

        CMS_Db::getInstance()->query($sql);
    }

    /**
     * Reemplaza las claves que aparecen en esta funcion
     * por los nombres establecidos para el nuevo modulo.
     * @param string $content
     * @param Zend_Models_Module $data
     * @return string
     */
    private function replaceContents($content, $data) {
        $content = str_replace("##view_name_plural##", $data->plural_name, $content);
        $content = str_replace("##view_name##", $data->name, $content);
        $content = str_replace("##name##", $data->system_name, $content);
        $content = str_replace("##caps_name##", ucwords($data->system_name), $content);
        $content = str_replace("##view_name_plural_no_caps##", strtolower($data->plural_name), $content);
        return $content;
    }


    private function simpleLangForm($action)
    {
         $form = new Zend_Form();
        $form->setAction("/admin/generator/$action")
                ->setMethod('post');
        $form->setAttrib("class", "jNice");
        $common = new Zend_Form_SubForm();
        $parent = $form->createElement("select", "parent");
        $modules = new CMS_Models_Module();
        $modules = $modules->getParentModules();
        $parent->setLabel('Modulo Padre:');
        $parent->addMultiOptions($this->formatCategories($modules));
        $name = $common->createElement('text', 'name');
        $name->setAttrib("class", "text-long");
        $name->addValidator('NotEmpty')->setLabel($this->view->t->_('Nombre:'))->setRequired(true);
        $name->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
        $system_name = $common->createElement('text', 'system_name');
        $system_name->setAttrib("class", "text-long");
        $system_name->addValidator('NotEmpty')->setLabel("Nombre en el sistema:")->setRequired(true);
        $system_name->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
        $plural = $common->createElement('text', 'plural');
        $plural->setAttrib("class", "text-long");
        $plural->addValidator('NotEmpty')->setLabel($this->view->t->_('Nombre en Plural:'))->setRequired(true);
        $plural->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
        $fields = $common->createElement("textarea", "fields");
        $fields->setAttrib("class", "text-long");
        $fields->addValidator('NotEmpty')->setLabel("Campos:")->setRequired(true);
        $fields->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
        $langFields = $common->createElement("textarea", "langFields");
        $langFields->setAttrib("class", "text-long");
        $langFields->addValidator('NotEmpty')->setLabel("Campos por idioma:")->setRequired(true);
        $langFields->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
        $common->addElement($parent);
        $common->addElement($name);
        $common->addElement($system_name);
        $common->addElement($plural);
        $common->addElement($fields);
        $common->addElement($langFields);
        $form->addSubForms(array("common" => $common));
        $form->addElement('submit', 'add', array('label' => $this->view->t->_('Aceptar')));
        return $form;
    }


    /**
     * Formulario de modulo simple, sin idiomas ni categorias
     * @param <type> $action
     * @return Zend_Form
     */
    private function langCategoryForm($action) {
        $form = new Zend_Form();
        $form->setAction("/admin/generator/$action")
                ->setMethod('post');
        $form->setAttrib("class", "jNice");
        $common = new Zend_Form_SubForm();
        $parent = $form->createElement("select", "parent");
        $modules = new CMS_Models_Module();
        $modules = $modules->getParentModules();
        $parent->setLabel('Modulo Padre:');
        $parent->addMultiOptions($this->formatCategories($modules));
        $name = $common->createElement('text', 'name');
        $name->setAttrib("class", "text-long");
        $name->addValidator('NotEmpty')->setLabel($this->view->t->_('Nombre:'))->setRequired(true);
        $name->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
        $system_name = $common->createElement('text', 'system_name');
        $system_name->setAttrib("class", "text-long");
        $system_name->addValidator('NotEmpty')->setLabel("Nombre en el sistema:")->setRequired(true);
        $system_name->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
        $plural = $common->createElement('text', 'plural');
        $plural->setAttrib("class", "text-long");
        $plural->addValidator('NotEmpty')->setLabel($this->view->t->_('Nombre en Plural:'))->setRequired(true);
        $plural->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
        $fields = $common->createElement("textarea", "fields");
        $fields->setAttrib("class", "text-long");
        $fields->addValidator('NotEmpty')->setLabel("Campos:")->setRequired(true);
        $fields->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
        $langFields = $common->createElement("textarea", "langFields");
        $langFields->setAttrib("class", "text-long");
        $langFields->addValidator('NotEmpty')->setLabel("Campos por idioma:")->setRequired(true);
        $langFields->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
        $common->addElement($parent);
        $common->addElement($name);
        $common->addElement($system_name);
        $common->addElement($plural);
        $common->addElement($fields);
        $common->addElement($langFields);
        $form->addSubForms(array("common" => $common));
        $form->addElement('submit', 'add', array('label' => $this->view->t->_('Aceptar')));
        return $form;
    }

    private function formatCategories($categories) {
        $options = array();

        foreach ($categories as $c) {
            $options[$c['id']] = $c['name'];
        }
        return $options;
    }

}